package com.bugreport.trackers.mantis128;

import java.math.BigInteger;
import java.rmi.RemoteException;

import javax.xml.rpc.ServiceException;

import org.apache.log4j.Logger;

import com.bugreport.model.Issue;
import com.bugreport.trackers.BugTrackerConnector;
import com.bugreport.trackers.clients.mantis128.IssueData;
import com.bugreport.trackers.clients.mantis128.MantisConnectLocator;
import com.bugreport.trackers.clients.mantis128.MantisConnectPortType;
import com.bugreport.utils.BugReportException;

public class Connector implements BugTrackerConnector {

	private static final Logger logger = Logger.getLogger(Connector.class);

	private Configuration config;
	private MantisConnectPortType client;
	private String username;
	private String password;
	private BigInteger projectId;
	private String categoryName;

	private Connector(Configuration config) throws BugReportException {

		MantisConnectLocator locator = new MantisConnectLocator();
		locator.setMantisConnectPortEndpointAddress(config.getWebServiceUrl());

		try {
			this.client = locator.getMantisConnectPort();
		} catch (ServiceException ex) {
			throw new BugReportException(300, ex, config.getBugTrackerKey(), config.getWebServiceUrl());
		}

		this.username = config.getUserLogin();
		this.password = config.getUserPassword();
		this.categoryName = config.getCategoryName();
		this.projectId = config.getProjectId();
		this.config = config;
	}

	public String reportIssue(Issue issue) throws BugReportException {

		try {

			logger.debug("Reporting new issue using Mantis 1.2.8 connector...");

			IssueData issueData = IssueDataProxy.newIssue(issue, projectId, categoryName);
			BigInteger issueId = client.mc_issue_add(username, password, issueData);
			logger.debug("Main part of issue #" + issueId.toString() + " reported to Mantis project");

			logger.debug("Attaching HTML page content to issue...");
			BigInteger htmlPageContentAttId = client.mc_issue_attachment_add(username, password, issueId, "content",
					"html", issue.getPageHtmlContent().getBytes());
			logger.debug("HTML page content added under attachment #" + htmlPageContentAttId.toString());

			logger.info("Issue #" + issueId.toString() + " successfully reported.");
			return issueId.toString();

		} catch (RemoteException ex) {
			throw new BugReportException(301, ex, config.getWebServiceUrl());
		}
	}

	public static Connector load(Configuration config) throws BugReportException {
		return new Connector(config);
	}
}
